package com.yuanfeng.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.activity.dto.JoinVoucherActivityDTO;
import com.yuanfeng.activity.dto.VoucherGoodsListDTO;
import com.yuanfeng.activity.dto.VoucherTemplateUpdateDTO;
import com.yuanfeng.activity.entity.ActivityVoucherTemplateEntity;
import com.yuanfeng.activity.feign.BusinessServiceClient;
import com.yuanfeng.activity.mapper.ActivityVoucherBaseMapper;
import com.yuanfeng.activity.mapper.ActivityVoucherTemplateMapper;
import com.yuanfeng.activity.service.ActivityVoucherTemplateService;
import com.yuanfeng.activity.vo.PlatformVoucherQueryVO;
import com.yuanfeng.activity.vo.VoucherGoodsQueryVO;
import com.yuanfeng.activity.vo.YfVoucherTemplateVO;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.LimitUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.goods.GdsListQueryResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class ActivityVoucherTemplateServiceImpl extends ServiceImpl<ActivityVoucherTemplateMapper, ActivityVoucherTemplateEntity>
    implements ActivityVoucherTemplateService{

    @Resource
    private ActivityVoucherTemplateMapper activityVoucherTemplateMapper;

    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Resource
    private ActivityVoucherBaseMapper activityVoucherBaseMapper;


    @Override
    public ResponseResult selectVoucherTemp(Map<String, Object> paraMap) {

        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token").toString());

        String limit = "Seller_Promotion_Voucher";
        ResponseResult result = new ResponseResult();
        Boolean torf = containLimits(userInfo, limit);
        if (!torf) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        paraMap.put("shopId", userInfo.getShopId().toString());

        IPage<YfVoucherTemplateVO> page=this.baseMapper.selectVoucherTemp(new Query<YfVoucherTemplateVO>().getPage(paraMap),
                paraMap);
        if (0 == page.getTotal()) {
            return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.VOUCHER_ISEMPTY.getMsg());
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.VOUCHER_TEMPLATE_SUCCESS.getMsg(),PageUtils.getPage(page));
    }

    @Override
    public ResponseResult deleteVoucherTemp(Map<String, String> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token"));
        String limit = "Seller_Promotion_Voucher";
        Boolean torf = containLimits(userInfo, limit);
        if (!torf) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        String shopId = userInfo.getShopId().toString();
        paraMap.put("shopId", shopId);

        Integer deleteOrNot = activityVoucherTemplateMapper.deleteVoucherTemp(paraMap);
        if (0 == deleteOrNot) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OPERATION_FAILED.getMsg());
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.DELETE_SUCCESS.getMsg());
    }

    /**
     *
     * @param userInfo 用户信息
     * @param limit    需要的权限字符串
     * @return
     */
    public Boolean containLimits(UserInfoVO userInfo, String limit) {
        Integer adminInteger = userInfo.getSellerIsAdmin();
        if (1 == adminInteger) {
            return true;
        }
        String limitsString = userInfo.getLimits();
        if (null == limitsString) {
            return false;
        }
        return true;
    }

    @Override
    public ResponseResult insertVoucherTemp(VoucherTemplateUpdateDTO param) {

        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if(userInfo == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        String shopId = userInfo.getShopId();
        param.setShopId(shopId);
        //代金券模版状态(1-有效,2-失效,3-审核中，4-审核失败)
        param.setVoucherTState(null == param.getVoucherTState() ? 1 : param.getVoucherTState());
        // 代金券类型：1-单个店铺
        param.setVoucherTType(1);
        param.setVoucherTCreatorId(userInfo.getUserId());
        String shopName = businessServiceClient.selectShopNameByShopId(shopId);
        param.setShopName(shopName);
        activityVoucherTemplateMapper.insertVoucherTemplate(param);
        if(param.getCommonIdList() != null && !param.getCommonIdList().isEmpty()){
            List<VoucherGoodsListDTO> goodsList = Lists.newArrayList();
            Integer voucherTId = param.getVoucherTId();
            activityVoucherTemplateMapper.update(null, new LambdaUpdateWrapper<ActivityVoucherTemplateEntity>()
                    .set(ActivityVoucherTemplateEntity::getIsShopVoucher,2)
                    .eq(ActivityVoucherTemplateEntity::getVoucherTId,voucherTId));
            JoinVoucherActivityDTO joinVoucherActivityDTO = new JoinVoucherActivityDTO();
            BeanUtils.copyProperties(param,joinVoucherActivityDTO);
            // 校验商品是否已有
            Integer count = this.baseMapper.selectVoucherGoodsCount(joinVoucherActivityDTO);
            if (null != count && count > 0) {
                return ResponseResult.fail(10012, "已有商品参加代金券，请勿重复添加");
            }

            for (Integer commonId : param.getCommonIdList()) {
                VoucherGoodsListDTO voucherGoodsList = new VoucherGoodsListDTO();
                voucherGoodsList.setShopId(shopId);
                voucherGoodsList.setCommonId(commonId);
                voucherGoodsList.setVoucherTId(voucherTId);
                goodsList.add(voucherGoodsList);
            }

            // 校验店铺是否已有
            joinVoucherActivityDTO.setShopId(shopId);
            Integer shopCount = this.baseMapper.selectVoucherShopCount(joinVoucherActivityDTO);

            joinVoucherActivityDTO.setWaitVerifyGoodsNum(param.getCommonIdList().size());
            joinVoucherActivityDTO.setAllGoodsNum(param.getCommonIdList().size());
            joinVoucherActivityDTO.setVoucherTId(voucherTId);
            if (null == shopCount || shopCount <= 0) {
                this.baseMapper.insertVoucherShop(joinVoucherActivityDTO);
            } else {
                this.baseMapper.updateVoucherShop(joinVoucherActivityDTO);
            }
            if(!goodsList.isEmpty()) {
                this.baseMapper.updateVoucherActivity(goodsList);
                this.baseMapper.updateVoucherTIdsBatch(goodsList);
            }
        }
        return ResponseResult.success(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.INSERT_VOUCHER_TEMPLATE_SUCCESS.getMsg());
    }

    @Override
    public ResponseResult queryPlatformVoucherList(Map<String,String> param) {
        UserInfoVO userInfo =null;
        String token=(String) param.get("token");
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        Integer shopId=null;
        if(StringUtils.isNotBlank(userInfoStr)) {
            userInfo = ParseTokenUtils.getUserInfoByToken(token);
            shopId = Integer.valueOf(userInfo.getShopId());
            if (shopId == null) {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(), BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
            }
        }
        List<PlatformVoucherQueryVO> result = activityVoucherTemplateMapper.selectPlatformVoucherList(shopId);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult joinVoucherActivity(JoinVoucherActivityDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        List<Integer> voucherTIds = param.getVoucherTIds();
        List<Integer> commonIdList = param.getCommonIdList();
        if (param.getVoucherTIds().size()==0){
            return ResponseResult.fail(10016, "未选择优惠券类型");
        }
        if (CollectionUtils.isEmpty(commonIdList)) {
            return ResponseResult.fail(10016, "未选择商品");
        }
        List<VoucherGoodsListDTO> goodsList = Lists.newArrayList();
        for (Integer voucherTId : voucherTIds) {
            param.setVoucherTId(voucherTId);
            // 校验商品是否已有
            Integer count = this.baseMapper.selectVoucherGoodsCount(param);
            if (null != count && count.intValue() > 0) {
                return ResponseResult.fail(10012, "已有商品参加代金券，请勿重复添加");
            }

            for (Integer commonId : commonIdList) {
                VoucherGoodsListDTO voucherGoodsList = new VoucherGoodsListDTO();
                voucherGoodsList.setShopId(shopId);
                voucherGoodsList.setCommonId(commonId);
                voucherGoodsList.setVoucherTId(voucherTId);
                goodsList.add(voucherGoodsList);
            }

            // 校验店铺是否已有
            param.setShopId(shopId);
            Integer shopCount = this.baseMapper.selectVoucherShopCount(param);

            param.setWaitVerifyGoodsNum(commonIdList.size());
            param.setAllGoodsNum(commonIdList.size());
            param.setVoucherTId(voucherTId);
            if (null == shopCount || shopCount.intValue() <= 0) {
                this.baseMapper.insertVoucherShop(param);
            } else {
                this.baseMapper.updateVoucherShop(param);
            }
        }

        if(null != goodsList && !goodsList.isEmpty()) {
            this.baseMapper.updateVoucherActivity(goodsList);
            this.baseMapper.updateVoucherTIdsBatch(goodsList);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryVoucherGoods(JoinVoucherActivityDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        param.setShopId(userInfo.getShopId());
        Page<VoucherGoodsQueryVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<VoucherGoodsQueryVO> result = this.baseMapper.selectVoucherGoods(page, param);
        return ResponseResult.success(PageUtils.getPage(result));
    }

    @Override
    public ResponseResult deleteSalesPromotionVoucher(Map<String, String> paraMap) {
        if((paraMap.get("shopId")=="" || paraMap.get("shopId")==null) && (paraMap.get("voucherPriceId")=="" || paraMap.get("voucherPriceId")==null)) {
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(paraMap.get("token").toString());
            String limit = "Seller_Promotion_Voucher";
            Boolean torf = LimitUtils.containLimits(userInfo, limit);
            if (!torf) {
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
            if(null!= userInfo.getShopId()){
                String shopId = userInfo.getShopId().toString();
                paraMap.put("shopId", shopId);
            }

        }
        activityVoucherBaseMapper.deleteVoucherBase(paraMap);
        //this.baseMapper.deleteVoucherTemp(paraMap);
        this.baseMapper.delete(new LambdaQueryWrapper<ActivityVoucherTemplateEntity>()
                       .eq(ActivityVoucherTemplateEntity::getShopId,paraMap.get("shopId"))
                       .eq(ActivityVoucherTemplateEntity::getVoucherTId,paraMap.get("voucherTId")));
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);

    }

    @Override
    public ResponseResult salesPromotionVoucherDetail(Map<String, Object> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(paraMap.get("token").toString());
        if (null != userInfo) {
            ActivityVoucherTemplateEntity entity = this.baseMapper.selectById(paraMap.get("voucherTId").toString());
            if(entity != null && entity.getIsShopVoucher() == 2){
                List<GdsListQueryResultVO> goodsList = activityVoucherBaseMapper.queryShopVoucherGoodsById(entity.getVoucherTId());
                entity.setGoodsList(goodsList);
            }
            return ResponseResult.success(entity);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult salesPromotionVoucherList(Map<String, Object> paraMap) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(paraMap.get("token").toString());
        if (null != userInfo) {
            //分页查询数据
            Page<ActivityVoucherTemplateEntity> page = new Page<>((Integer) paraMap.get("page"), (Integer) paraMap.get("limit"));
            IPage<ActivityVoucherTemplateEntity> results = this.baseMapper.salesPromotionVoucherList(page, paraMap);

            return ResponseResult.success(PageUtils.getPage(results));
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult salesPromotionVoucherUpdate(Map<String, Object> paraMap) {

        int result=this.baseMapper.update(null,new LambdaUpdateWrapper<ActivityVoucherTemplateEntity>()
                       .set(paraMap.containsKey("voucherTState"),ActivityVoucherTemplateEntity::getVoucherTState,paraMap.containsKey("voucherTState")?paraMap.get("voucherTState").toString():null)
                       .set(paraMap.containsKey("voucherTRecommend"),ActivityVoucherTemplateEntity::getVoucherTRecommend,paraMap.containsKey("voucherTRecommend")?paraMap.get("voucherTRecommend").toString():null)
                       .set(paraMap.containsKey("voucherTTitle"),ActivityVoucherTemplateEntity::getVoucherTTitle,paraMap.containsKey("voucherTTitle")?paraMap.get("voucherTTitle").toString():null)
                       .eq(ActivityVoucherTemplateEntity::getVoucherTId,paraMap.get("voucherTId")));
        if(result>0){
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);

    }


}




